//
//  UIColor-Extension.swift
//  XKPageView
//
//  Created by 徐凯 on 2017/6/7.
//  Copyright © 2017年 XK. All rights reserved.
//

import UIKit

extension UIColor {
    
    // MARK:- 在extension扩展构造函数必须在init前加convenience
    convenience init(r : CGFloat, g : CGFloat, b : CGFloat) {
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
    }
    
    // MARK:- 16进制
    convenience init?(hexString : String) {
        // 判断字符串长度 > 6
        guard hexString.characters.count >= 6 else {
            
            return nil
        }
         // 将字符串转成大写
        var hexTempStr = hexString.uppercased()
        if(hexTempStr.hasPrefix("0X") || hexTempStr.hasPrefix("##"))
        {
            hexTempStr = (hexTempStr as NSString).substring(from: 2)
        }
        
        // 判断 #开头
        if(hexTempStr.hasPrefix("#"))
        {
            hexTempStr = (hexTempStr as NSString).substring(from: 1)
        }
        
        // r:FF g:99 b:33
        var range = NSRange(location: 0, length: 2)
        let rHex = (hexTempStr as NSString).substring(with: range)
        
        range.location = 2
        let gHex = (hexTempStr as NSString).substring(with: range)
        
        range.location = 4
        let bHex = (hexTempStr as NSString).substring(with: range)
        
        // 16 进制转值
        
        var r : UInt32 = 0
        var g : UInt32 = 0
        var b : UInt32 = 0
        Scanner(string: rHex).scanHexInt32(&r)
        Scanner(string: gHex).scanHexInt32(&g)
        Scanner(string: bHex).scanHexInt32(&b)

        
        self.init(r : CGFloat(r), g : CGFloat(g), b : CGFloat(b))
    }
    
    class func randomColor() -> UIColor {
        return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
    }
}
